package com.tensquare.friend.controller;

import com.tensquare.friend.clinet.UserClient;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by DUZEYU on 2018/12/30.
 */
@RestController
@RequestMapping(value = "/friend")
@CrossOrigin // 解决项目之间跨域问题
public class FriendController {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FriendService friendService;
    @Autowired
    private UserClient userClient;

    @RequestMapping(value = "/like/{friendid}/{type}",method = RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid,@PathVariable String type){
        // 验证是否登陆，并且拿到当前登陆人的Id
        Claims claims = (Claims) request.getAttribute("claims_user");
        if(null == claims){
            // 说明当前用户没有用户角色
            return new Result(false,StatusCode.LOGINERROR,"权限不足");
        }
        //得到当前的用户id
        String userId = claims.getId();
        // 判断是添加好友还是删除好友
        if (null != type){
            if ("1".equals(type)){
                //添加好友
                int flag = friendService.addFriend(userId,friendid);
                if (flag == 0){
                    return new Result(false, StatusCode.ERROR,"不能重复添加好友");
                }
                if (flag == 1){
                    // 用户关注数
                    userClient.updateFanscountAndFollowcount(userId,friendid,1);
                    return new Result(true, StatusCode.OK,"添加成功");
                }
            }else if ("1".equals(type)){
                // 添加非好友
                int flag = friendService.addNoFriend(userId,friendid);
                if (flag == 0){
                    return new Result(false, StatusCode.ERROR,"不能重复添加非好友");
                }
                if (flag == 1){
                    return new Result(true, StatusCode.OK,"添加成功");
                }
            }
            return new Result(false, StatusCode.ERROR,"参数异常");
        }else{
            return new Result(false, StatusCode.ERROR,"参数异常");
        }
    }

    /**
     * 删除好友
     * @return
     */
    @RequestMapping(value = "/{friendid}",method = RequestMethod.DELETE)
    public Result deleteFriend(@PathVariable String friendid){
        // 验证是否登陆，并且拿到当前登陆人的Id
        Claims claims = (Claims) request.getAttribute("claims_user");
        if(null == claims){
            // 说明当前用户没有用户角色
            return new Result(false,StatusCode.LOGINERROR,"权限不足");
        }
        //得到当前的用户id
        String userId = claims.getId();
        friendService.deleteFriend(userId,friendid);
        // 删除好友  并删除粉丝数 关注数
        userClient.updateFanscountAndFollowcount(userId,friendid,-1);
        return new Result(true,StatusCode.OK,"删除成功");
    }
}
